<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use App\Http\Logic\Login;
use Illuminate\Http\JsonResponse;
use function is_null;

class JWTMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param Request $request
     * @param Closure $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next): mixed
    {
        $token = $request->headers->get('ACCESS-TOKEN');

        // 没有token
        if (is_null($token)) {
            return $this->NotFoundTokenError();
        }
        $payload = Login::getInstance()->parseToken($token);
        // token 不正确
        if (!$payload) {
            return $this->InvalidTokenError();
        }
        $request->jwt = $payload;
        return $next($request);
    }

    protected function NotFoundTokenError(): JsonResponse
    {
        return response()->json([
            "code" => 10000,
            "msg" => "JWT Token Not Found!",
            "data" => [],
        ]);
    }

    protected function InvalidTokenError(): JsonResponse
    {
        return response()->json([
            "code" => 10000,
            "msg" => "Invalid JWT Token",
            "data" => [],
        ]);
    }

}
